/**
 * 
 */
package com.gopay.checkorder.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.task.BankCountDownLatch;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.bank.CmbConstants;
import com.gopay.common.constants.bank.CmbQueryRespone;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.cmb.ebank.pay.CmbB2cMessage;
import com.gopay.common.domain.bank.cmb.ebank.query.CmbB2cResMessage;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.cashier.BankCardType;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.domain.cps.vo.InAccInfo;
import com.gopay.common.util.DateUtils;
import com.gopay.remote.bank.BankInteractRemoteService;

/**
 * @CheckOrderCmbBankImpl.java
 * @author Ryan
 * @2013-11-11 下午2:24:32  www.gopay.com.cn Inc.All rights reserved.
 */
public class CheckOrderCmbBankImpl implements BankOrderService{

    private Logger logger = Logger.getLogger("CMB");
    @Resource(name = "bankClient")
    private BankInteractRemoteService bankClient;
    
    @Override
    public CheckOrderResult checkOrder(BankOrder bankOrder, String target) {
        CheckOrderResult checkOrderResult = new CheckOrderResult();
        checkOrderResult.setOrderId(bankOrder.getOrderId());
        
        CmbB2cMessage message =  new CmbB2cMessage();
        message.setOrderId(bankOrder.getOrderId());
        message.setBillNo(bankOrder.getOutOrderId());
        message.setBankOrderId(bankOrder.getOutOrderId());
        message.setBank(BankConstants.BANK_LOGO_CMB);
        message.setBankIntrChann(BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()));
		message.setBankBusProd(BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));
        message.setDate(DateUtils.format(bankOrder.getSendBankTm(),"yyyyMMdd"));

        Result result = new Result();
        try {
            result = bankClient.query(message);
        } catch (Exception e) {
            logger.error("bankClient fail.", e);
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
            checkOrderResult.setErrMsg("银行对账异常");
            return checkOrderResult;
        }

        if (result == null || !result.isSuccess()) {
            logger.error("bankClient fail. result is null");
            if(result ==null || ProcCodeConstants.PROC_CODE_100E6037.equals(result.getResultCode())){
            	BankCountDownLatch.failIncrease(bankOrder.getBankCode());
            	checkOrderResult.setCommunicateError(true);
			}
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
            checkOrderResult.setErrMsg("系统返回对账结果为空");
            checkOrderResult.setSuccess(false);
            return checkOrderResult;
        }

        CmbB2cResMessage res = (CmbB2cResMessage) result.getDefaultModel();
        if (res == null) {
            // 查询订单为空
            logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:" + ProcCodeConstants.PROC_CODE_100E6022+ " err:bis query is null.");
            checkOrderResult.setSuccess(false);
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
            checkOrderResult.setErrMsg("银行返回对账结果为空");
            return checkOrderResult;
        }

        if (!CmbConstants.CMB_QUERY_STATUS_SUCCESS_INT.equals(res.getQueryResult())) {
            // 查询订单错误
            logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:" + res.getQueryResult() + " err:"+ res.getErrorMsg());
            checkOrderResult.setSuccess(false);
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);         
            checkOrderResult.setErrMsg(res.getErrorMsg());
            return checkOrderResult;
        }

        checkOrderResult.setOrderId(bankOrder.getOrderId());
        checkOrderResult.setAmount(res.getRetQueryMoney());
        //成功处理
        if (StringUtils.equals(CmbConstants.CMB_ORDER_STATUS_SUCCESS,res.getOrderStatus())) {
            checkOrderResult.setSuccess(true);
            InAccInfo accInfo = new InAccInfo();
            accInfo.setOrderId(bankOrder.getOrderId());
            accInfo.setAmount(res.getRetQueryMoney());
            accInfo.setRetCode("00");
            accInfo.setCardType(BankCardType.Unknown.toString());
            checkOrderResult.setAccInfo(accInfo);
            logger.error("招行B2C订单" + bankOrder.getOrderId()+"的交易"+CmbQueryRespone.getName(res.getOrderStatus()));
        } else {
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
            if(res.getErrorMsg()!=null || !"".equals(res.getErrorMsg())){
                checkOrderResult.setErrMsg(res.getErrorMsg());
                logger.error("招行B2C订单" + bankOrder.getOrderId()+"的交易"+CmbQueryRespone.getName(res.getOrderStatus()));
            }else{
                checkOrderResult.setErrMsg("招行订单查询未明确");
                logger.error("招行B2C订单" + bankOrder.getOrderId() + "未返回交易状态");
            }
            checkOrderResult.setSuccess(false);
            return checkOrderResult;
        }

        return checkOrderResult;

    }

	@Override
	public BankOrder getDbOrder() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BaseMessage dayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<CheckOrderResult> checkDayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result getDayendMsg(String string) {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
		// TODO Auto-generated method stub
		return null;
	}

}
